import React, { useState, useEffect } from 'react';
import { Select, Row, Col, message, Transfer, Button } from 'antd';
import services from '../../../../../../services/api';

const initState = {
  name: '',
  appkeyList: [],
  appKeyData: [],
};

const Add = (props) => {
  const { value, closeModal } = props;
  const [params, setParams] = useState({ ...initState, id: value.id });
  const [organOptions, setOrganOptions] = useState([]);

  useEffect(() => {
    getOrganList();
  }, []);

  const handleSelectChange = async (name) => {
    if (!name) return;
    const {
      data: { authList, notAuthList },
    } = await services.authorizeInfo.getAppkeyByOrgan(params.id, name);
    const appkeyList = authList.map((item) => item.id);
    const appKeyData = [...authList, ...notAuthList].map((item) => ({ ...item, key: item.id, title: item.appKey }));
    setParams((prevState) => ({
      ...prevState,
      appkeyList,
      appKeyData,
      name,
    }));
  };

  // 获取机构
  const getOrganList = async () => {
    const { data, code, msg } = await services.authorizeInfo.organList();
    if (code) return message.error(msg);
    setOrganOptions(data);
  };

  const handleTranferChange = (nextTargetKeys) => {
    setParams((prevState) => ({
      ...prevState,
      appkeyList: nextTargetKeys,
    }));
  };

  const rendeInfoNodes = () => [
    {
      label: '接口名',
      value: value.name,
    },
    {
      label: '机构名',
      value: (
        <Select value={params.name} style={{ width: '100%' }} placeholder='请选择机构' onChange={handleSelectChange}>
          {organOptions.map(({ id, name }) => (
            <Select.Option key={id} value={id}>
              {name}
            </Select.Option>
          ))}
        </Select>
      ),
    },
  ];

  const handleSubmit = async () => {
    if (!params.name) return message.warning('请选择机构');
    const { msg, code } = await services.authorizeInfo.addAuthAppkey(params);
    if (code) return message.warning(msg);
    message.success(msg);
    closeModal();
  };

  return (
    <>
      {rendeInfoNodes().map(({ label, value }) => (
        <Row style={{ marginBottom: '20px' }} key={label}>
          <Col span={4}>{label}</Col>
          <Col span={16}>{value}</Col>
        </Row>
      ))}
      <Transfer
        dataSource={params.appKeyData}
        onChange={handleTranferChange}
        titles={['列表一', '列表二']}
        targetKeys={params.appkeyList}
        render={(item) => item.title}
      />
      <div style={{ marginTop: '20px', textAlign: 'center' }}>
        <Button className='marr10' onClick={() => closeModal()}>
          取消
        </Button>
        <Button type='primary' onClick={handleSubmit} htmlType='submit'>
          确定
        </Button>
      </div>
    </>
  );
};
export default Add;
